package cn.edu.scnu.semart.order.controller;

import cn.edu.scnu.semart.model.order.Alipay;
import cn.edu.scnu.semart.model.order.Order;
import cn.edu.scnu.semart.model.order.OrderDTO;
import cn.edu.scnu.semart.order.mapper.OrderMapper;
import cn.edu.scnu.semart.order.service.OrderService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Controller
@CrossOrigin
@RequestMapping("/payment")
public class AlipayController {

    @Value("${alipay.gatewayUrl}")
    private String gatewayUrl;

    @Value("${alipay.appId}")
    private String appId;

    @Value("${alipay.merchantPrivateKey}")
    private String merchantPrivateKey;

    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;

    @Value("${alipay.notifyUrl}")
    private String notifyUrl;

    @Value("${alipay.returnUrl}")
    private String returnUrl;

    @Autowired
    private OrderService orderService;  // 用来更新订单状态

    @Autowired
    private OrderMapper orderMapper;

    // 支付接口，生成支付宝支付页面链接
    @GetMapping("/pay")
    @ResponseBody
    public String pay(@RequestParam String price, @RequestParam String subject,@RequestParam String outTradeNo) throws AlipayApiException {
        // 校验订单支付状态
        System.out.println("调用"+outTradeNo);

        Order order = orderService.getByPayTradeNo(outTradeNo);
        if (order == null) {
            return "订单不存在";
        }
        if (!"pending_payment".equals(order.getStatus())) {
            return "该订单已支付或已关闭，不能重复支付";
        }
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, merchantPrivateKey, "json", "utf-8", alipayPublicKey, "RSA2");

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);

        request.setBizContent("{" +
                "\"out_trade_no\":\"" + outTradeNo + "\"," + // 商户订单号为当前时间戳
                "\"total_amount\":" + price + "," + // 支付金额
                "\"subject\":\"" + subject + "\"," + // 订单标题
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}" // 产品码
        );

        String form = alipayClient.pageExecute(request).getBody();
        return form; // 返回支付表单
    }

    /* =================  重新支付接口（新增） ================= */


    // 支付宝支付通知处理接口
    @PostMapping("/notify")
    @ResponseBody
    public String handleNotify(HttpServletRequest request, HttpSession session) throws AlipayApiException {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
        if (signVerified) {
            System.out.println("Async notification received and verified.");
            String outTradeNo = request.getParameter("out_trade_no");
            String tradeStatus = request.getParameter("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                Order order = orderService.getByPayTradeNo(outTradeNo);
                if (order != null) {
                    orderService.updateOrderStatus(order.getOrderId(), "pending_delivery");
                    System.out.println("Order status updated to PAID.");
                } else {
                    System.out.println("No order found for payTradeNo: " + outTradeNo);
                }
            } else {
                System.out.println("Trade status is not SUCCESS. Actual value: " + tradeStatus);
            }
            System.out.println("=== notify hit ===");
            return "success";
        } else {
            System.out.println("Async notification verification failed.");
            return "failure";
        }
    }


    // 支付完成后的页面跳转
    @GetMapping("/return")
    public String handleReturn(HttpServletRequest request) throws AlipayApiException {
        // 支付完成后的跳转页面（可以自定义）
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
        if (signVerified) {
            System.out.println("Async notification received and verified.");
            String outTradeNo = request.getParameter("out_trade_no");
            String tradeStatus = request.getParameter("trade_status");
            System.out.println("============================trade_status============"+tradeStatus);
            if (true) {
                Order order = orderService.getByPayTradeNo(outTradeNo);
                if (order != null) {
                    orderService.updateOrderStatus(order.getOrderId(), "pending_delivery");
                    System.out.println("Order status updated to PAID.");
                } else {
                    System.out.println("No order found for payTradeNo: " + outTradeNo);
                }
            } else {
                System.out.println("Trade status is not SUCCESS. Actual value: " + tradeStatus);
            }
            System.out.println("=== notify hit ===");
        } else {
            System.out.println("Async notification verification failed.");
        }
        return "redirect:http://localhost:8082/#/myOrder";  // 返回支付完成后的页面
    }
}
